<?php
/**
 * Created by PhpStorm.
 * User: JX
 * Date: 2017/8/16
 * Time: 14:44
 */

namespace App\Http\Controllers\API\WeChat;


use App\Http\Controllers\Controller;
use App\Models\WeChat;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use App\Models\WechatMessage;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\PredisCache;
use EasyWeChat\Message\Text;
class WeChatMessageController extends Controller
{
    private $openPlatform = '';
    public $days = array();

    public function __construct(Application $app)
    {
        $predis = app('redis')->connection()->client();// connection($name), $name 默认为 `default`
        $cacheDriver = new PredisCache($predis);
        $app->cache = $cacheDriver;
        $this->openPlatform = $app->open_platform;
    }
    public function messageReply(Request $request){
        $id = $request->get('message_id');
        $reply = $request->get('reply');
        $openPlatform = $this->openPlatform;
        try{
            $message_info = WechatMessage::query()->where(['id'=>$id])->first();
            if(!$message_info){
                throw new \Exception('未找到消息');
            }
            $wechat = WeChat::query()->where(['id' =>  $message_info ->w_id])->first();
            if(!$wechat){
                throw new \Exception('未找到该公众号');
            }
            $app = $openPlatform->createAuthorizerApplication($wechat->authorizer_appid, $wechat->authorizer_refresh_token);
            $message = new Text(['content' =>  $reply]);
            $user = WechatUser::query()->where(['id'=>$message_info->user_open_id])->first();
            if(!$user){
                throw new \Exception('未找到该用户');
            }
            // dd($message->user_open_id,$user);
            $result =json_decode($app->staff->message($message)->to($user->open_id)->send());
            if($result->errcode !=0){
                throw new \Exception('消息发送失败');
            }
            $message_info->is_return = 1;
            if(!$message_info->save()){
                throw new \Exception('消息状态失败');
            }
            return ['success'=>'true','message'=>'回复成功'];
        }catch (\Exception $e){
            return response(['success' => 'false', 'message' =>$e->getMessage()],406);
        }

    }
    public function index(Request $request)
    {
        $queryString = $request->get('query', '');
        $w_id =  $request->get('w_id');
        $models = WeChatMessage::with('Users')->where(['w_id'=>$w_id])
            ->whereHas('Users', function ($query) use ($queryString) {
                $query->where('nick_name', 'like', '%' . $queryString . '%');
            })
            ->orderBy('id','desc')
            ->paginate(10);
        return $models;
    }
    /**
     * 添加公众号
     * @param Request $request
     * @return mixed
     */
    public function store(Request $request)
    {
        $model = new WeChatMessage();
        $model->fill($request->all());
        if ($model->save()) {
            return $model;
        } else {
            return response($model->getErrors()->toArray(), 406);
        }
    }


    /**
     * 修改员工
     * @param User $User
     * @param Request $request
     * @return mixed
     */
    public function update(WeChatMessage $WeChatMessage, Request $request)
    {
        $WeChatMessage->fill($request->all());
        if ($WeChatMessage->save()) {
            return $WeChatMessage;
        } else {
            return response($WeChatMessage->getErrors()->toArray(), 406);
        }
    }


    /**
     * 删除
     * @param $id
     * @return mixed
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return ['state' => 'success'];
        } catch (\Exception $e) {
            return ['state' => 'failed', 'message' => $e->getMessage()];
        }
    }


    /**
     * 返回单个实例
     * @param User $user
     * @return mixed
     */
    public function show($id)
    {
        return $this->findModel($id);
    }




    /**
     * @param $id
     * @return Staff
     */
    public function findModel($id)
    {
        $model = WeChatMessage::with('Users')->findOrFail($id);
        return $model;
    }

}